package com.googlecode.connectlet.web;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletHandler;

import com.googlecode.connectlet.util.Base64;

public class TestHttp extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String auth = request.getHeader("Authorization");
		if (auth != null && auth.startsWith("Basic ")) {
			response.getOutputStream().write(Base64.decode(auth.substring(6)));
		} else {
			response.setHeader("WWW-Authenticate", "Basic realm=\"HTTP Test\"");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
		}
	}

	public static void main(String[] args) throws Exception {
		Server server = new Server();
		SocketConnector connector = new SocketConnector();
		connector.setPort(80);
		server.addConnector(connector);
		ServletHandler handler = new ServletHandler();
		handler.addServletWithMapping(TestHttp.class, "/");
		server.setHandler(handler);
		server.start();
		server.join();
	}
}